import { router } from "./index";
import UserModel from '@/moduls/userModel';
import RoleModel from '@/moduls/roleModel';
import md5 from 'blueimp-md5';

/**
 * 登录接口
 * @param req 请求对象
 * @param res 响应对象
 */
router.post("/login",(req,res)=>{
  const {username,password} = req.body
  UserModel.findOne({username,password:md5(password)}).then(user=>{
      if(user){
          if(user.role_id){
              // 普通用户
              RoleModel.findOne({_id:user.role_id}).then(role=>{
                  if(!role) {
                      return res.send({status:1,msg:'角色不存在'});
                  }
                  const userObj = user.toObject();
                  (userObj as any).role = role;
                  res.send({status:0,data:userObj})
              })
          }else{
              // 超级管理员
              const userObj = user.toObject();
              (userObj as any).role = {menus:[]};
              res.send({status:0,data:userObj})
          }
          
      }else{
          res.send({status:1,msg:'用户名或密码错误'})
      }
  }).catch(error=>{
      res.send({status:1,msg:'登录异常，请重新尝试'})
  })
})